package com.hl.sfzy.controller.content;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import com.hl.sfzy.entity.content.Knowlege;
import com.hl.sfzy.service.content.KnowledgeService;
import com.hl.sfzy.utils.R;

@RestController
@RequestMapping("/knowledge")
public class KnowledgeController {


    @Autowired
    private KnowledgeService knowledgeService;

    @GetMapping("/getKnowledges")
    public R<List<Knowlege>> getKnowledges(){
        List<Knowlege> knowledges = knowledgeService.getKnowledges();
        return Optional.ofNullable(knowledges).map(R::success).orElseGet(() -> R.failure("查询失败"));
    }
    @GetMapping("/getKnowledgesPage")
    public R<List<Knowlege>> getKnowledges(@RequestParam("pageNo") Integer pageNo, @RequestParam("pageSize")Integer pageSize){
        List<Knowlege> knowledges = knowledgeService.getKnowledgesPage(pageNo,pageSize);
        return Optional.ofNullable(knowledges).map(R::success).orElseGet(() -> R.failure("查询失败"));
    }

    @GetMapping("/getKnowlegeById/{id}")
    public R<Knowlege> getKnowlegeById(@PathVariable("id") Long id){
        Knowlege knowlege = knowledgeService.getKnowlegeById(id);
        System.out.println(id);
        return Optional.ofNullable(knowlege).map(R::success).orElseGet(() -> R.failure("查询失败"));
    }


    @GetMapping("/getKnowledgeByTitle")
    public R<List<Knowlege>> getKnowledgeByTitle( String knowlegeName){
        List<Knowlege> knowleges = knowledgeService.getKnowlegeByName(knowlegeName);
        return Optional.ofNullable(knowleges).map(R::success).orElseGet(() -> R.failure("查询失败"));
    }

    @PostMapping("/addKnowlege")
    public R<Integer> addKnowlege(@RequestBody Knowlege knowlege){
        int i = knowledgeService.addKnowlege(knowlege);
        return i > 0 ? R.success(i) : R.failure("添加失败");
    }


    @DeleteMapping("/removeKnowlege/{id}")
    public R<Integer> removeKnowlege(@PathVariable("id") Long id){
        int i = knowledgeService.removeKnowlege(id);
        return i > 0 ? R.success(i) : R.failure("删除失败");
    }


    @PutMapping("/updateKnowlege")
    public R<Integer> updateKnowlege(@RequestBody Knowlege knowlege){
        System.out.println(knowlege);
        int i = knowledgeService.updateKnowlege(knowlege);
        return i > 0 ? R.success(i) : R.failure("更新失败");
    }

    @GetMapping("/searchKnowledges")
    public R<List<Knowlege>> searchKnowledges(String key,LocalDateTime starTime,LocalDateTime endTime){
        List<Knowlege> knowledges = knowledgeService.searchKnowledges(key,starTime,endTime);
        return Optional.ofNullable(knowledges).map(R::success).orElseGet(() -> R.failure("查询失败"));
    }
    
}
